package com.ruoyi.industry.service.impl;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.District;
import com.ruoyi.industry.domain.ProjectApartment;
import com.ruoyi.industry.domain.ProjectPark;
import com.ruoyi.industry.domain.SpaceIndustry;
import com.ruoyi.industry.mapper.*;
import com.ruoyi.industry.service.IProjectApartmentService;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 公寓Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-08
 */
@Service
public class ProjectApartmentServiceImpl implements IProjectApartmentService {
    private static final Logger log = LoggerFactory.getLogger(ProjectApartmentServiceImpl.class);

    @Autowired
    private ProjectApartmentMapper projectApartmentMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 查询公寓
     *
     * @param id 公寓主键
     * @return 公寓
     */
    @Override
    public ProjectApartment selectProjectApartmentById(Long id) {
        return projectApartmentMapper.selectProjectApartmentById(id);
    }

    /**
     * 查询公寓列表
     *
     * @param projectApartment 公寓
     * @return 公寓
     */
    @Override
    public List<ProjectApartment> selectProjectApartmentList(ProjectApartment projectApartment) {
        //租赁价格
        if (projectApartment.getApartmentLeasePrice() != null) {
            String[] split = projectApartment.getApartmentLeasePrice().split("~");
            projectApartment.setApartmentLeasePriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectApartment.setApartmentLeasePriceHigh(Long.parseLong(split[1]));
            }
        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectApartment.setSupplyUserId(SecurityUtils.getUserId());
//        }
//        //所属城市
//        List<Long> districtIds = new ArrayList<Long>();
//        if (projectApartment.getCityId()!=null){
//            districtIds.add(projectApartment.getCityId());
//            projectApartment.setCityIds(districtIds);
//        }else if (projectApartment.getCityId()==null && projectApartment.getProvinceId() != null){
//            //查询省份下的城市
//            districtIds.addAll(districtMapper.selectDistrictIdList(projectApartment.getProvinceId()));
//            districtIds.add(projectApartment.getProvinceId());
//            projectApartment.setCityIds(districtIds);
//        }
        List<ProjectApartment> projectApartmentList = projectApartmentMapper.selectProjectApartmentListz(projectApartment);
//        for (ProjectApartment apartment : projectApartmentList) {
//            SysUser sysUser = spaceIndustryMapper.selectSysUserById(apartment.getServicePhone());
//            if (sysUser!=null){
//                if (sysUser.getNickName()!=null&&!sysUser.getNickName().equals("")) {
//                    apartment.setContactName(sysUser.getNickName());
//                }else {
//                    apartment.setContactName(sysUser.getUserName());
//                }
//                apartment.setContactPhone(sysUser.getPhonenumber());
//            }
//        }
        return projectApartmentList;
    }

    /**
     * 新增公寓
     *
     * @param projectApartment 公寓
     * @return 结果
     */
    @Override
    public int insertProjectApartment(ProjectApartment projectApartment) {
        projectApartment.setSupplyUserId(SecurityUtils.getUserId());
        if (projectApartment.getApprovalState() == null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectApartment.setApprovalState(1L);//审核通过
//            } else {
                projectApartment.setApprovalState(0L);//待审核
//            }
        }
        projectApartment.setCreateTime(DateUtils.getNowDate());
        projectApartment.setSerialNumber(IdUtils.fastSimpleUUID());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectApartment, spaceIndustry);
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectApartment.getCreateTime());
        spaceIndustry.setSpaceId(projectApartment.getSerialNumber());
        spaceIndustry.setSupplyUserId(projectApartment.getSupplyUserId());
        spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
        return projectApartmentMapper.insertProjectApartment(projectApartment);
    }

    private static void extracted(ProjectApartment projectApartment, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(6);
        spaceIndustry.setReleaseType(projectApartment.getReleaseType());
        spaceIndustry.setApprovalState(projectApartment.getApprovalState());
        spaceIndustry.setProvinceId(projectApartment.getProvinceId());//省份
        spaceIndustry.setCityId(projectApartment.getCityId());//城市
//        spaceIndustry.setAreaId();//区域
        spaceIndustry.setSupplyType(projectApartment.getSupplyType());//服务类型
        spaceIndustry.setParkId(String.valueOf(projectApartment.getParkId()));
        spaceIndustry.setHeating(projectApartment.getApartmentHeating());//供暖
        spaceIndustry.setRefrig(projectApartment.getApartmentRefrig());//制冷
        spaceIndustry.setPower(projectApartment.getApartmentPower());//电力
        spaceIndustry.setGas(projectApartment.getApartmentGas());//燃气
        spaceIndustry.setLeasePrice(projectApartment.getApartmentLeasePrice());//出售价格
        spaceIndustry.setSellPrice(projectApartment.getApartmentSellPrice());//租赁价格
        spaceIndustry.setCoverResource(projectApartment.getCoverResource());//封面资源
        spaceIndustry.setSpaceName(projectApartment.getApartmentName());//园区名称
        spaceIndustry.setSpaceAllSize(projectApartment.getApartmentAllSize());//空间总面积
        spaceIndustry.setTop(projectApartment.getTop());//置顶
        spaceIndustry.setRecomState(projectApartment.getRecomState());//热门推荐
    }

    /**
     * 修改公寓
     *
     * @param projectApartment 公寓
     * @return 结果
     */
    @Override
    public int updateProjectApartment(ProjectApartment projectApartment) {
        if (projectApartment.getApprovalState() == null) {
            projectApartment.setApprovalState(0L);//待审核
        }
        projectApartment.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectApartment, spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectApartment.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectApartment.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByApartmentId(spaceIndustry);
        return projectApartmentMapper.updateProjectApartment(projectApartment);
    }

    /**
     * 批量删除公寓
     *
     * @param ids 需要删除的公寓主键
     * @return 结果
     */
    @Override
    public int deleteProjectApartmentByIds(Long[] ids) {
        List<ProjectApartment> projectApartments = projectApartmentMapper.selectProjectApartmentByIds(ids);
        List<String> pathList = new ArrayList<>();
        for (ProjectApartment projectApartment : projectApartments) {
            spaceIndustryMapper.deleteSpaceRecomById("公寓",projectApartment.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectApartment.getVrResource(),
                    projectApartment.getImgResource(),
                    projectApartment.getCoverResource(),
                    projectApartment.getVrcover(),
                    projectApartment.getQrCode()
            );
        }
        spaceIndustryMapper.deleteSpaceIndustryByProjectApartmentIds(ids);
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        return projectApartmentMapper.deleteProjectApartmentByIds(ids);
    }

    /**
     * 删除公寓信息
     *
     * @param id 公寓主键
     * @return 结果
     */
    @Override
    public int deleteProjectApartmentById(Long id) {
        ProjectApartment projectApartment = projectApartmentMapper.selectProjectApartmentById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectApartment.getVrResource(),
                projectApartment.getImgResource(),
                projectApartment.getCoverResource(),
                projectApartment.getVrcover(),
                projectApartment.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("公寓",projectApartment.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectApartmentId(id);
        return projectApartmentMapper.deleteProjectApartmentById(id);
    }
    /**
     * 查询公寓
     *
     * @param spaceId 编号
     * @param show
     * @return 结果
     */
    @Override
    public Map<String, Object> selectProjectApartmentByNumber(String spaceId, boolean show) {
        ProjectApartment projectApartment = projectApartmentMapper.selectProjectApartmentByNumber(spaceId);
        if (SecurityUtils.getUserId()!=null&&SecurityUtils.getUserId()!=0) {
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(),spaceId);
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectApartmentMapper.updatePageViews(spaceId);
            }
            if (list != null && list.size() != 0) {
                projectApartment.setCollectState(1L);
            } else {
                projectApartment.setCollectState(0L);
            }
        }else {
            projectApartment.setCollectState(0L);
        }
        if (projectApartment.getProvinceId()!=null){
            District district = districtMapper.selectDistrictById(projectApartment.getProvinceId());
            projectApartment.setCityName(district.getName());
        }
        if (projectApartment.getCityId()!=null){
            District district = districtMapper.selectDistrictById(projectApartment.getCityId());
            projectApartment.setCityName(projectApartment.getCityName()+district.getName());
        }
//        if (projectApartment.getAreaId()!=null){
//            District district = districtMapper.selectDistrictById(projectApartment.getAreaId());
//            projectApartment.setCityName(projectApartment.getCityName()+district.getName());
//        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectApartment.getServicePhone());
        if (sysUser!=null){
            projectApartment.setContactName(sysUser.getNickName());
            projectApartment.setContactPhone(sysUser.getPhonenumber());
            projectApartment.setQrCode(sysUser.getCodePic());
        }
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectApartment.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("space",projectApartment);
        if (projectApartment.getParkId()!=null) {
            ProjectPark projectPark = projectParkMapper.selectProjectParkById(projectApartment.getParkId());
            map.put("park",projectPark);
        }else {
            map.put("park",null);
        }
        return map;
    }

    @Override
    public int deleteProjectApartmentBySerialNumber(String spaceId) {
        ProjectApartment projectApartment = projectApartmentMapper.selectProjectApartmentByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectApartment.getVrResource(),
                projectApartment.getImgResource(),
                projectApartment.getCoverResource(),
                projectApartment.getVrcover(),
                projectApartment.getQrCode()
        );
        spaceIndustryMapper.deleteSpaceRecomById("公寓",projectApartment.getId());
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceIndustryByProjectApartmentId(projectApartment.getId());
        return projectApartmentMapper.deleteProjectApartmentById(projectApartment.getId());
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);

    @Override
    public String importUser(List<ProjectApartment> projectApartmentList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(projectApartmentList) || projectApartmentList.size()==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;
        for (ProjectApartment projectApartment : projectApartmentList) {
            int i = projectApartmentList.indexOf(projectApartment);

            if (i==0&&projectApartment.getApartmentName().equals("公寓名称")){
                continue;
            }
            count++;
            try {
                if (projectApartment.getApprovalState()==null||STATE.contains(projectApartment.getApprovalState())){
                    projectApartment.setApprovalState(0L);
                }
                if (projectApartment.getSupplyUserId()==null){
                    projectApartment.setApprovalState(SecurityUtils.getUserId());
                }
                if (projectApartment.getApartmentName()==null||projectApartment.getApartmentName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少公寓名称");
                    break;
                }
                projectApartment.setCreateBy(SecurityUtils.getUsername());
                projectApartment.setCreateTime(DateUtils.getNowDate());
                projectApartmentMapper.insertProjectApartment(projectApartment);
                successNum++;
                successMsg.append("<br/>" + successNum + "、公寓 " + projectApartment.getApartmentName() + " 导入成功");
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、公寓 " + projectApartment.getApartmentName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectApartment modal = projectApartmentMapper.selectProjectApartmentById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("需求类型：" + modal.getSupplyType() + "<w:br/>");
        stringBuffer.append("园区类型：" + modal.getParkType() + "<w:br/>");
        stringBuffer.append("区域位置：" + modal.getParkAreaAddress() + "<w:br/>");
        stringBuffer.append("求租价格：" + modal.getApartmentLeasePrice() + "<w:br/>");
        stringBuffer.append("求购价格：" + modal.getApartmentSellPrice() + "<w:br/>");
        stringBuffer.append("需求面积：" + modal.getApartmentNeedSize() + "<w:br/>");
        stringBuffer.append("户型：" + modal.getApartmentHouse() + "<w:br/>");
        stringBuffer.append("装修程度：" + modal.getApartmentRenova() + "<w:br/>");
        stringBuffer.append("客梯：" + modal.getApartmentElevatorPeople() + "<w:br/>");
        stringBuffer.append("客梯负载：" + modal.getApartmentElevatorPeopleLoad() + "<w:br/>");
        stringBuffer.append("货梯：" + modal.getApartmentElevatorCargo() + "<w:br/>");
        stringBuffer.append("货梯负载：" + modal.getApartmentElevatorCargoLoad() + "<w:br/>");
        stringBuffer.append("安防设施：" + modal.getApartmentFireControl() + "<w:br/>");
        stringBuffer.append("应急系统：" + modal.getApartmentEmergency() + "<w:br/>");
        stringBuffer.append("供暖：" + modal.getApartmentHeating() + "<w:br/>");
        stringBuffer.append("制冷：" + modal.getApartmentRefrig() + "<w:br/>");
        stringBuffer.append("新风系统：" + modal.getApartmentNather() + "<w:br/>");
        stringBuffer.append("电量：" + modal.getApartmentPower() + "<w:br/>");
        stringBuffer.append("燃气：" + modal.getApartmentGas() + "<w:br/>");
        stringBuffer.append("水：" + modal.getApartmentWater() + "<w:br/>");
        stringBuffer.append("周边交通情况：" + modal.getApartmentTraffic() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
